package com.sh.common.core.utils;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class BlockChainUtils {

    public static final String ACCEPT = "application/json";
    public static final String X_API_KEY = "yfo5FOf437H07B7nCtmYF3fsVikA3hq9EQeWY7H9ASgDOk5RC6zaSwq7jYUG44ig";
    // ok-access-key
    public static final String OK_ACCESS_KEY = "22f353f8-302f-4125-b953-d9f7ffb4c969";

    /**
     * 自动生成交易hash
     * @return 交易hash
     */
    public static String generatorTxHash(){
        String param = String.valueOf(System.nanoTime());
        return getSHA256StrJava(param).toLowerCase();
    }

    public static String getSHA256StrJava(String str) {
        MessageDigest messageDigest;
        String txHash = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
            byte[] bb = messageDigest.digest();
            txHash = byteToString(bb);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return txHash;
    }

    public static String byteToString(byte[] bytes){
        StringBuilder encryptSirBub = new StringBuilder();
        for (byte aByte : bytes) {
            if (Integer.toHexString(0xFF & aByte).length() == 1) {
                encryptSirBub.append("0").append(Integer.toHexString(0xFF & aByte));
            } else {
                encryptSirBub.append(Integer.toHexString(0xFF & aByte));
            }
        }
        return encryptSirBub.toString().toUpperCase();
    }

    /**
     * getDecodeTransactionByHash
     * @param txHash
     * @return
     */
    public static String getDecodeTransactionByHash(String txHash) {
        HttpRequest request = HttpUtil.createGet("https://deep-index.moralis.io/api/v2.2/transaction/" + txHash + "/verbose");

        Map<String, String> headMap = new HashMap<>();
        headMap.put("Accept", ACCEPT);
        headMap.put("X-API-Key", X_API_KEY);

        request.headerMap(headMap, true);
        request.form("chain", "bsc");

        HttpResponse response = request.execute();

        return response.body();
    }

    /**
     * Get Wallet Transaction History
     * @param address
     * @return
     */
    public static String getWalletTransactionHistory(String address) {
        HttpRequest request = HttpUtil.createGet("https://deep-index.moralis.io/api/v2.2/wallets/" + address + "/history");

        Map<String, String> headMap = new HashMap<>();
        headMap.put("Accept", ACCEPT);
        headMap.put("X-API-Key", X_API_KEY);

        request.headerMap(headMap, true);
        request.form("chain", "bsc");
        //request.form("from_date", LocalDateTimeUtil.now().minusHours(9));
        //request.form("to_date", LocalDateTimeUtil.now().minusHours(8));
        request.form("order", "DESC");
        request.form("limit", 100);

        HttpResponse response = request.execute();

        return response.body();
    }

    /**
     * Get ERC20 Token Price
     * @param address
     * @return
     */
    public static String getERC20TokenPrice(String address) {
        HttpRequest request = HttpUtil.createGet("https://deep-index.moralis.io/api/v2.2/erc20/" + address + "/price");

        Map<String, String> headMap = new HashMap<>();
        headMap.put("Accept", ACCEPT);
        headMap.put("X-API-Key", X_API_KEY);

        request.headerMap(headMap, true);
        request.form("chain", "bsc");
        request.form("include", "percent_change");

        HttpResponse response = request.execute();

        return response.body();
    }

    /**
     * Get NFT owners by contract
     * @param address of the NFT contract
     * @return
     */
    public static String getNFTOwnersByContract(String address, String cursor) {

        HttpRequest request = HttpUtil.createGet("https://deep-index.moralis.io/api/v2.2/nft/" + address + "/owners");

        Map<String, String> headMap = new HashMap<>();
        headMap.put("Accept", ACCEPT);
        headMap.put("X-API-Key", X_API_KEY);

        request.headerMap(headMap, true);
        request.form("chain", "bsc");
        request.form("format", "decimal");
        request.form("cursor", cursor);

        HttpResponse response = request.execute();

        return response.body();
    }

    /**
     * Get NFT owners by contract
     * @param address of the NFT contract
     * @return
     */
    public static List<String> getNFTOwnersByContractApi(String address) {

        List<String> addressList = new ArrayList<>();

        String result = getNFTOwnersByContract(address, null);

        return addressList;
    }

    /***
     * 查询scroll代币价格
     * @return
     */
    public static String queryScrollPrice() {
        HttpRequest request = HttpUtil.createGet("https://www.oklink.com/api/v5/explorer/tokenprice/price-multi");

        Map<String, String> headMap = new HashMap<>();
        //headMap.put("Accept", ACCEPT);
        headMap.put("Ok-Access-Key", OK_ACCESS_KEY);

        request.headerMap(headMap, true);
        request.form("chainShortName", "SCROLL");
        request.form("tokenContractAddress", "0xd29687c813D741E2F938F4aC377128810E217b1b");
        request.form("chainId", 534352);

        HttpResponse response = request.execute();

        return response.body();
    }



}
